package uk.ac.cam.echo.app;

import java.io.IOException;
import java.net.UnknownHostException;
import uk.ac.cam.echo.social.FacebookClient;
import uk.ac.cam.echo.social.SimpleEventListener;
import uk.ac.cam.echo.social.StringEventListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class LoginActivity extends ExtendedActivity
{
	private final Object scannerLock = new Object();
	private boolean isProcessingTag = false;

	private final String programID = "166978770079248"; // the ID associated
														// with the app
	// registered on FB
	private final String groupID = "269265166481425"; // the ID associated with
														// a particular FB group

	private final String hostIP = "192.168.15.212";
	private final int hostPort = 44444;
	private String facebookID = null;

	private Scanner scanner;

	View scanningAnimation;
	View loadingAnimation;
	Button retryButton;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login);
		scanner = new Scanner(this);

		scanningAnimation = findViewById(R.id.loginScanningAnimation);
		loadingAnimation = findViewById(R.id.loginLoadingAnimation);
		retryButton = (Button) findViewById(R.id.loginRetry);

		retryButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				hideView(retryButton);
				attemptToLogIn();
			}
		});

		attemptToLogIn();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		scanner.resume();
	}

	@Override
	public void onPause()
	{
		super.onPause();
		scanner.pause();
	}

	private void attemptToLogIn()
	{
		if (FacebookClient.getInstance() == null)
			FacebookClient.init(groupID, programID);
		if (!FacebookClient.getInstance().sessionIsValid())
		{
			FacebookClient.getInstance().authorize(new SimpleEventListener()
			{
				@Override
				public void respondToEvent()
				{
					onPostAuth();
				}
			}, new StringEventListener()
			{
				@Override
				public void respondToEvent(String result)
				{
					showOKMessage("Facebook authorization failed, please retry and check your internet connectivity.\n" + result);
					showView(retryButton);
					hideView(scanningAnimation);
				}

			}, self);
		}
		else
		{
			onPostAuth();
		}
	}

	private void onPostAuth()
	{
		showMessage("Facebook authorization successful", true);
		showView(loadingAnimation);
		FacebookClient.getInstance().getUsersFacebookIDAsync(new StringEventListener()
		{
			@Override
			public void respondToEvent(String result)
			{
				facebookID = result;
				showMessage("FacebookID retrieved", true);

				self.runOnUiThread(new Runnable()
				{

					@Override
					public void run()
					{
						scanner.startSniffing();
					}
				});

				showView(scanningAnimation);
				hideView(loadingAnimation);
			}
		},

		new StringEventListener()
		{
			@Override
			public void respondToEvent(String result)
			{
				showOKMessage("Failed to retrieve your facebook ID, please try again and check your internet connection.\n" + result);
				showView(retryButton);
				hideView(scanningAnimation);
			}
		});
	}

	@Override
	public void onNewIntent(Intent i)
	{
		// make sure one doesn't scan tags faster than they are processed!
		synchronized (scannerLock)
		{
			final String tag = Scanner.decode(i);
			if (tag != null && !isProcessingTag)
			{
				isProcessingTag = true;

				Thread t = new Thread()
				{
					@Override
					public void run()
					{
						try
						{
							DBInt.getInstance(tag, facebookID, hostIP, hostPort);
							hideView(loadingAnimation);
							Intent intent = new Intent(self, EchoActivity.class);
							self.startActivity(intent);
							self.finish();
						}
						catch (UnknownHostException e)
						{
							showOKMessage("Problem connecting to the server, please check your internet connection.\n" + e);
						}
						catch (IOException e)
						{
							showOKMessage("Problem connecting to the server, please check your internet connection.\n" + e);
						}
						finally
						{
							hideView(loadingAnimation);
							showView(retryButton);

							synchronized (scannerLock)
							{
								isProcessingTag = false;
							}
						}
					}
				};
				t.start();
			}
		}
	}
}
